package vno.fux.mediator
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.MouseEvent;
	
	import vno.fux.character.CharacterLayer;
	import vno.fux.events.MapEvent;
	import vno.fux.events.NpcEvent;
	import vno.fux.map.MapLayer;
	import vno.fux.ui.UiLayer;
	import vno.fux.BasePoint;

	public class LayerMediator extends EventDispatcher
	{
		private static var instance:LayerMediator;
		private var _mapLayer:MapLayer;
		private var _characterLayer:CharacterLayer;
		private var _uiLayer:UiLayer;
		public function LayerMediator(pvt:PrivateClass)
		{
			//initMapLayerManager();
			//initCharacterLayerManager();
		}
		private function mapListen():void
		{
			_mapLayer.addEventListener(MapEvent.MOVE, moveHandler);
			_mapLayer.addEventListener(MapEvent.DIRECTION, directionHandler);
			_mapLayer.addEventListener(MapEvent.START_MOVE, moveStateHandler);
			_mapLayer.addEventListener(MapEvent.END_MOVE, moveStateHandler);
			_mapLayer.addEventListener(MapEvent.UNREACH, moveStateHandler);
		}
		
		private function characterListen():void
		{
			_characterLayer.addEventListener(NpcEvent.CLICK, npcClickHandler);
		}
		
		private function uiListen():void
		{
			_uiLayer.addEventListener(MapEvent.START_MOVE, _mapLayer.handleMoveNeed);
		}

		private function npcClickHandler(event:NpcEvent):void
		{
			_uiLayer.handleNpcEvent(event);
		}
		
		public function moveStateHandler(event:MapEvent):void
		{
			_characterLayer.handleMoveState(event);
			_uiLayer.handleMoveState(event);
		}
		
		public function moveHandler(event:MapEvent):void
		{
			//trace(typeof((event as MapEvent)));
			_characterLayer.handleMapMove(event);
			_uiLayer.handleMapMove(event);
		}

		public function directionHandler(event:MapEvent):void
		{
			//trace(typeof((event as MapEvent)));
			_characterLayer.handleDirection(event);
		}
		
		public static function init():void
		{
			if(LayerMediator.instance)
			{
				throw new Error("You can't init the LayerMediator twice!")
			}
			LayerMediator.instance = new LayerMediator(new PrivateClass);
		}
		
		public static function getInstance():LayerMediator
		{
			return LayerMediator.instance;
		}
		
		public function set mapLayer(value:MapLayer):void
		{
			_mapLayer = value;
			mapListen();
		}
		public function set characterLayer(value:CharacterLayer):void
		{
			_characterLayer = value;
			characterListen();
		}
		public function set uiLayer(value:UiLayer):void
		{
			_uiLayer = value;
			_uiLayer.mediator = this;
			uiListen();
		}
		public function getMapPos():BasePoint
		{
			return _mapLayer.getPos();
		}
		//		public function get characterLayer():CharacterLayer
//		{
//			return _characterLayer;
//		}
	}
}
class PrivateClass
{
	public function PrivateClass()
	{
	}
}